package com.atguigu.srb.core.controller.admin;


import com.alibaba.excel.EasyExcel;
import com.atguigu.srb.common.result.R;
import com.atguigu.srb.core.pojo.dto.ExcelDictDTO;
import com.atguigu.srb.core.pojo.entity.Dict;
import com.atguigu.srb.core.service.DictService;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

/**
 * <p>
 * 数据字典 前端控制器
 * </p>
 *
 * @author LiLi
 * @since 2021-09-23
 */
@RestController
@RequestMapping("/admin/core/dict")
@Slf4j
//@CrossOrigin
public class AdminDictController {

    @Autowired
    DictService dictService;

    @ApiOperation("导出excel")
    @GetMapping("export")
    public R export(HttpServletResponse response) throws IOException {
        List<ExcelDictDTO> excelDictDTOS = dictService.listDictData();
        String fileName = URLEncoder.encode("尚融宝数据字典","UTF-8").replaceAll("\\+","%20");
                response.setCharacterEncoding("UTF-8");
                response.setContentType("application/vnd.ms-excel");
                response.setHeader("Content-disposition","attachment;filename*=utf-8‘’"+fileName+".xlsx");
        EasyExcel
                .write(response.getOutputStream(),ExcelDictDTO.class)
                .sheet("字典表测试数据")
                .doWrite(excelDictDTOS);
        return R.ok().message("上传成功");
    }


    @ApiOperation("上传excel")
    @PostMapping("import")
    public R batchImport(@RequestParam("file")MultipartFile multipartFile){
        //调用service业务层上传功能
        dictService.importData(multipartFile);
        return R.ok().message("上传成功");
    }

    @ApiOperation("根据父id查询字典集合")
    @GetMapping("listByParentId/{parentId}")
    public R listByParentId(
        @ApiParam("字典表的父id")
        @PathVariable("parentId") Long parentId ){

        List<Dict> list = dictService.listByParentId(parentId);
        return R.ok().data("list",list);
    }
}

